//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
using SPUserPoll.Business.Components;

namespace SPUserPoll.Presentation.WebParts.UserControls
{
    public partial class PollResultControl : System.Web.UI.UserControl
    {
        #region Properties
        /// <summary>
        /// The Id of the Poll
        /// </summary>
        private string PollID
        {
            get { return PollingWebPart.SPUserPollID; }
        }

        private Control _pollingWebpart = null;

        /// <summary>
        /// Access to the polling webpart
        /// </summary>
        private PollDisplayWebPart PollingWebPart
        {
            get
            {
                if (_pollingWebpart == null)
                    _pollingWebpart = this;

                if (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                {
                    _pollingWebpart = this;
                    while (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                    {
                        _pollingWebpart = _pollingWebpart.Parent;
                    }
                }
                return _pollingWebpart as PollDisplayWebPart;
            }
        }

        /// <summary>
        /// Thd ID of the WebPart
        /// </summary>
        private string WebPartID
        {
            get { return PollingWebPart.ID; }
        }

        /// <summary>
        /// The poll status
        /// </summary>
        private bool PollPublished
        {
            get { return PollingWebPart.SPUserPollPublished; }

        }

        /// <summary>
        /// Question of the poll
        /// </summary>
        private string PollQuestion
        {
            get { return PollingWebPart.SPUserPollQuestion; }
        }


        /// <summary>
        /// Poll result type
        /// </summary>
        private Types.PollResultType PollResultType
        {
            get { return PollingWebPart.SPUserPollResultType; }
        }


        /// <summary>
        /// Determines the display type of the poll
        /// </summary>
        private Types.PollResultDisplay PollResultDisplay
        {
            get { return PollingWebPart.SPUserPollResultDisplay; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            BindResults();
            litPollQuestion.Text = PollQuestion;

            //Decide to show textual or graph results
            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.Textual)
                phTextualResult.Visible = true;
            else
                phGraphResult.Visible = true;
        }

        public void BindResults()
        {
            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.Textual)
            {
                //load the poll answers
                repResults.DataSource = ManageLists.GetResultTableForPoll(PollID);
                repResults.DataBind();
            }
            else
            {
                //draw graph
                if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.BarChart 
                    || PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.ColumnChart)
                    DrawBarStyleCharts();

                //draw graph
                if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.DoughnutChart 
                    || PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.PieChart)
                    DrawPieStyleCharts();
            }
        }

        /// <summary>
        /// Draw the pie style charts
        /// </summary>
        private void DrawPieStyleCharts()
        {
            //get the datatable
            DataTable pollTable = ManageLists.GetResultTableForPoll(PollID);

            // Create new data series and set it's visual attributes
            Series series = new Series("Results");

            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.DoughnutChart)
                series.ChartType = SeriesChartType.Doughnut;

            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.PieChart)
                series.ChartType = SeriesChartType.Pie;

            series.IsValueShownAsLabel = true;
            series.BorderWidth = 1;
            series.ShadowOffset = 2;

            foreach (DataRow row in pollTable.Rows) {
                //get item info
                string answer = row["Answer"].ToString();
                int count = System.Convert.ToInt32(row["Count"]);
                decimal percentage = System.Convert.ToDecimal(row["Percentage"])/100;

                //add point
                DataPoint item = new DataPoint();
                item.AxisLabel = answer;
                if (count > 0 && PollingWebPart.SPUserPollResultType != Types.PollResultType.None)
                {
                    item.Label = GetCountAndPercentageLabel(count, percentage);
                }
                else
                {
                    item.Label = " "; //make sure it is empty
                }

                item.ToolTip = string.Format("{0} vote(s), {1}", count, percentage.ToString("P"));    
                item.SetValueY(count);
                series.Points.Add(item);

            }
         
            // Add series into the chart's series collection
            chartDisplay.Series.Add(series);

            chartDisplay.Width = PollingWebPart.SPUserPollChartWidth;
            chartDisplay.Height = PollingWebPart.SPUserPollChartHeight;
            
            //show a chart background if configured
            if (PollingWebPart.SPUserPollShowChartBackground == true)
            {
                chartDisplay.BackGradientStyle = GradientStyle.TopBottom;
                chartDisplay.BackColor = Color.LightBlue;
            }

            //Draw a legend
            // Add header separator to the table
            chartDisplay.Legends.Add("Legend"); ;
            chartDisplay.Legends["Legend"].HeaderSeparator = LegendSeparatorStyle.Line;
            chartDisplay.Legends["Legend"].HeaderSeparatorColor = Color.Gray;
            chartDisplay.Legends["Legend"].Docking = Docking.Bottom;

            // Add Color column      
            LegendCellColumn colorColumn = new LegendCellColumn();
            colorColumn.ColumnType = LegendCellColumnType.SeriesSymbol;
            colorColumn.HeaderText = "Color";
            colorColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(colorColumn);

            // Add answer cell column      
            LegendCellColumn answerColumn = new LegendCellColumn();
            answerColumn.ColumnType = LegendCellColumnType.Text;
            answerColumn.Text = "#AXISLABEL";
            answerColumn.HeaderText = "Answer";
            answerColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(answerColumn);

            // Add vote cell column      
            LegendCellColumn votesColumn = new LegendCellColumn();
            votesColumn.Text = "#VALY";
            votesColumn.HeaderText = "Votes";
            votesColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(votesColumn);

            // Add percentage cell column      
            LegendCellColumn percentageColumn = new LegendCellColumn();
            percentageColumn.Text = "#PERCENT";
            percentageColumn.HeaderText = "Percentage";
            percentageColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(percentageColumn);





        }

        /// <summary>
        /// Draw the bar style charts
        /// </summary>
        private void DrawBarStyleCharts()
        {
            //get the datatable
            DataTable pollTable = ManageLists.GetResultTableForPoll(PollID);

            // Create new data series and set it's visual attributes
            Series series = new Series("Results");

            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.BarChart)
                series.ChartType = SeriesChartType.Bar;

            if (PollingWebPart.SPUserPollResultDisplay == Types.PollResultDisplay.ColumnChart)
                series.ChartType = SeriesChartType.Column;


            series.BorderWidth = 1;
            series.ShadowOffset = 2;
            series.Color = Color.LightGray;
            series.LabelBackColor = Color.White;
            series.LabelBorderColor = Color.Black;
            series.LabelBorderWidth = 1;

            foreach (DataRow row in pollTable.Rows)
            {
                //get item info
                string answer = row["Answer"].ToString();
                int count = System.Convert.ToInt32(row["Count"]);
                decimal percentage = System.Convert.ToDecimal(row["Percentage"]) / 100;

                //add point
                DataPoint item = new DataPoint();
                item.AxisLabel = answer;
                if (count > 0 && PollingWebPart.SPUserPollResultType != Types.PollResultType.None)
                    item.Label = GetCountAndPercentageLabel(count, percentage);

                item.ToolTip = string.Format("{0} vote(s), {1}", count, percentage.ToString("P"));
                item.SetValueY(count);
                series.Points.Add(item);

            }

            // Add series into the chart's series collection
            chartDisplay.Series.Add(series);

            chartDisplay.Width = PollingWebPart.SPUserPollChartWidth;
            chartDisplay.Height = PollingWebPart.SPUserPollChartHeight;

            //show a chart background if configured
            if (PollingWebPart.SPUserPollShowChartBackground == true)
            {
                chartDisplay.BackGradientStyle = GradientStyle.TopBottom;
                chartDisplay.BackColor = Color.LightBlue;
            }

        }


        /// <summary>
        /// Constructs a label based on the user choice
        /// </summary>
        /// <param name="count"></param>
        /// <param name="percentage"></param>
        /// <returns></returns>
        private string GetCountAndPercentageLabel(int count, decimal percentage)
        {
            string displayPercentage = percentage.ToString("P");

            if (PollResultType == Types.PollResultType.Percentage)
            {
                return string.Format("{0}", displayPercentage);
            }
            else if (PollResultType == Types.PollResultType.Count)
            {
                return string.Format("{0}", count);
            }
            else
            {
                return string.Format("{0} ({1})", displayPercentage, count);
            }
        }

        protected void repResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DataRowView rowView = e.Item.DataItem as DataRowView;
                string answer = rowView["Answer"].ToString();
                int count = System.Convert.ToInt32(rowView["Count"]);
                decimal percentage = System.Convert.ToDecimal(rowView["Percentage"])/100;

                Literal litAnswer = e.Item.FindControl("litAnswer") as Literal;
                Literal litResult = e.Item.FindControl("litResult") as Literal;

                //write answer
                litAnswer.Text = answer;

                //set result text
                litResult.Text = GetCountAndPercentageLabel(count, percentage);
            }
        }
    }
}